<template>
  <div class="app-container">
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      :title="type === 'add' ? '新建投资组合' : '编辑投资组合'"
      width="800px"
      @close="dialogClose"
      class="aMDialog"
    >
      <div class="container">
        <el-form
          size="mini"
          :inline="true"
          :model="dataForm"
          :rules="dataRule"
          ref="dataForm"
          class="aMFrom"
          @keyup.enter.native="submitHandle()"
          label-width="110px"
        >
          <el-form-item prop="compositionName" label="组合名称：">
            <el-input
              size="mini"
              v-model="dataForm.compositionName"
              placeholder="请输入"
              style="width: 300px"
            ></el-input>
          </el-form-item>
          <el-form-item prop="createdTime" label="开始时间：">
            <el-date-picker
              v-model="dataForm.createdTime"
              type="date"
              size="mini"
              style="width: 200px"
              placeholder="投资时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item prop="mark" label="添加备注：">
            <el-input
              size="mini"
              v-model="dataForm.mark"
              placeholder="请输入"
              style="width: 300px"
            ></el-input>
          </el-form-item>
          <el-form-item prop="indexType" label="对标指数：">
            <indexSelectTree
              :width="200"
              size="mini"
              :multiple="false"
              :indexType.sync="dataForm.indexType"
              @getIndexName="getIndexNameHandle"
            ></indexSelectTree>
          </el-form-item>
          <!-- 投资分类 -->
          <div class="card-list">
            <div class="tit">投资分类（必填）</div>
            <div
              class="card-list-content"
              v-for="(item, i) in dataForm.childTypeList"
              :key="item.id"
            >
              <div class="card-list-title">
                <el-form-item
                  label-width="90px"
                  :prop="`childTypeList.${i}.classfyName`"
                  label="分类名称："
                >
                  <el-input
                    :class="{ border_red: item.classfyNameRule }"
                    v-model="item.classfyName"
                    @input="checkNoEmpty(i, 'classfyName')"
                    placeholder="请输入"
                    style="width: 200px"
                  ></el-input>
                </el-form-item>
                <el-form-item
                  label-width="83px"
                  :prop="`childTypeList.${i}.indexType`"
                  label="对标指数："
                >
                  <indexSelectTree
                    :class="{ border_red: item.indexTypeRule }"
                    :width="200"
                    size="mini"
                    @getIndexName="checkNoEmpty(i, 'indexType')"
                    :multiple="false"
                    :indexType.sync="item.indexType"
                  ></indexSelectTree>
                </el-form-item>
                <div style="width: 100px">
                  <el-button
                    size="mini"
                    style="padding: 4px 10px; height: 28px; margin-right: 5px"
                    v-show="dataForm.childTypeList.length > 1"
                    @click="delectClassfyHandle(i)"
                  >
                    <i class="iconfont icon-ashbin"></i>
                    删除分类
                  </el-button>
                </div>
              </div>
              <div class="card-list-content-title">
                <div style="min-width: 40px; text-align: center">移动</div>
                <div style="min-width: 500px">投资名称</div>
                <div style="min-width: 100px">操作</div>
              </div>
              <div
                class="card-list-content-child"
                v-for="(citem, index) in item.classifyStrategyExt"
                :key="citem.id"
              >
                <div
                  class="handle-move"
                  style="min-width: 40px; text-align: center"
                >
                  <i class="iconfont icon-tuodongweizhi icon-move"></i>
                </div>
                <el-form-item
                  style="margin: 0"
                  :prop="`childTypeList.${i}.classifyStrategyExt.${index}.strategyName`"
                  label=""
                >
                  <div @click="selectSubInvestHandle(i, index, 'radio')">
                    <el-input
                      v-model="citem.strategyName"
                      :class="{ border_red: citem.strategyNameRule }"
                      readonly
                      placeholder="请选择投资"
                      style="width: 500px"
                      suffix-icon="el-icon-arrow-right"
                    ></el-input>
                  </div>
                </el-form-item>
                <div style="min-width: 100px">
                  <el-button
                    size="mini"
                    style="padding: 4px 10px; height: 28px; margin-right: 5px"
                    v-show="
                      dataForm.childTypeList[i].classifyStrategyExt.length > 1
                    "
                    @click="delClassfyChildHandle(i, index)"
                  >
                    <i class="iconfont icon-ashbin"></i>
                    删除
                  </el-button>
                </div>
              </div>
              <div style="display: flex; justify-content: space-between">
                <el-button
                  size="mini"
                  @click="selectSubInvestHandle(i, 0, 'check')"
                  style="width: 48%; margin: 10px 1% 0 1%; border-style: dashed"
                >
                  <i class="iconfont icon-add-circle"></i>
                  添加投资
                </el-button>
                <el-button
                  size="mini"
                  @click="addOrUpdateHandle(i, 0, 'check')"
                  style="width: 48%; margin: 10px 1% 0 1%; border-style: dashed"
                >
                  <i class="iconfont icon-add-circle"></i>
                  新建投资
                </el-button>
              </div>
            </div>
            <el-button
              @click="addClassfyHandle"
              style="width: 100%; margin-top: 16px"
            >
              <i class="iconfont icon-add-circle"></i>
              添加分类
            </el-button>
          </div>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false" style="width: 100px">
            取 消
          </el-button>
          <el-button type="primary" @click="submitHandle" style="width: 100px">
            确 定
          </el-button>
        </div>
      </div>
    </el-dialog>
    <investOpen
      v-if="subInvestVisible"
      ref="subInvestOpen"
      title="投资列表"
      :type="investTypeDialog"
      :nolink="true"
      :userId="userId"
      @selctSubInvestName="selctSubInvestName"
      @selCheckctSubInvestName="selCheckctSubInvestName"
    ></investOpen>
    <investAddOrUpdateDialog
      ref="investAddOrUpdateDialog"
      @closeOpen="selectSubInvestHandle(combination_i, 0, 'check')"
      type="add"
      :row="{}"
      :addOrUpdateView.sync="investAddOrUpdateView"
    ></investAddOrUpdateDialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  configInvestComposition,
  editInvestComposition,
} from "@/api/afterInvest";
import investOpen from "@/views/afterManage/component/investOpen.vue";
import indexSelectTree from "@/components/investComn/indexSelectTree.vue";
import { parseTime } from "@/utils";
import investAddOrUpdateDialog from "@/views/afterManage/investList/dialog";

export default {
  name: "",
  components: { indexSelectTree, investOpen, investAddOrUpdateDialog },
  computed: {
    ...mapGetters(["userId"]),
  },

  data() {
    return {
      dialogVisible: false,
      strategyVisible: false,
      subInvestVisible: false,
      investAddOrUpdateView: false,
      combination_i: 0,
      dataForm: {
        compositionName: "", // 组合名称
        createdBy: "", //创建人
        createdTime: "", // 创建时间
        hasClassify: "", //下属分类标识
        indexType: "", //对标指数
        initMoney: 0, // 初始权益
        investManageEquity: 0, // 权益
        investManageShare: 0, // 份额
        mark: "", // 备注
        strategyId: 0, // 策略id
        updatedBy: 0, // 更新人
        updatedTime: "", //更新时间
        childTypeList: [],
      },
      investTypeDialog: "radio",
      dataRule: {
        compositionName: [
          { required: true, message: "请输入组合名称", trigger: "blur" },
        ],
      },
      strategy_i: 0,
      strategy_index: 0,
    };
  },
  props: {
    type: {
      type: String,
      default: "add",
    },
    row: {
      type: Array | Object,
    },
    addOrUpdateView: {
      type: Boolean,
    },
  },
  watch: {
    addOrUpdateView: function (newVal) {
      this.dialogVisible = newVal;
      console.log(this.row);
      if (newVal) {
        this.$nextTick(() => {
          this.$refs["dataForm"].resetFields();
          if (this.row.compositionId) {
            editInvestComposition({
              compositionId: this.row.compositionId,
            }).then((res) => {
              this.dataForm.compositionId =
                res.body.strategyCompositionVo.compositionId; //创建人
              this.dataForm.compositionName =
                res.body.strategyCompositionVo.compositionName; //创建人
              this.dataForm.createdBy =
                res.body.strategyCompositionVo.createdBy; //创建人
              this.dataForm.createdTime =
                res.body.strategyCompositionVo.createdTime; // 创建时间
              this.dataForm.hasClassify =
                res.body.strategyCompositionVo.hasClassify; //下属分类标识
              this.dataForm.indexType =
                res.body.strategyCompositionVo.indexType; //对标指数
              this.dataForm.initMoney =
                res.body.strategyCompositionVo.initMoney; // 初始权益
              this.dataForm.investManageEquity =
                res.body.strategyCompositionVo.investManageEquity; // 权益
              this.dataForm.investManageShare =
                res.body.strategyCompositionVo.investManageShare; // 份额
              this.dataForm.mark = res.body.strategyCompositionVo.mark; // 备注
              this.dataForm.strategyId =
                res.body.strategyCompositionVo.strategyId; // 策略id
              this.dataForm.updatedBy =
                res.body.strategyCompositionVo.updatedBy; // 更新人
              this.dataForm.updatedTime =
                res.body.strategyCompositionVo.updatedTime; //更新时间
              this.dataForm.childTypeList = res.body.strategyClassifyVo;
            });
          } else {
            this.dataInit();
          }
        });
      }
    },
  },
  created() {},
  methods: {
    dataInit() {
      this.dataForm = {
        compositionName: "", // 组合名称
        createdBy: "", //创建人
        createdTime: "", // 创建时间
        hasClassify: "", //下属分类标识
        indexType: "", //对标指数
        indexName: "",
        initMoney: 0, // 初始权益
        investManageEquity: 0, // 权益
        investManageShare: 0, // 份额
        mark: "", // 备注
        strategyId: 0, // 策略id
        updatedBy: 0, // 更新人
        updatedTime: "", //更新时间
        childTypeList: [
          {
            classfyName: "",
            indexType: "",
            classifyStrategyExt: [],
          },
        ],
      };
    },
    addClassfyHandle() {
      this.dataForm.childTypeList.push({
        classfyName: "",
        indexType: "",
        classifyStrategyExt: [],
      });
    },
    delClassfyChildHandle(i, index) {
      this.$confirm(
        `确认删除投资名称【${this.dataForm.childTypeList[i].classifyStrategyExt[index].strategyName}】此条数据？`,
        "提示",
        { type: "warning" }
      )
        .then((_) => {
          this.dataForm.childTypeList[i].classifyStrategyExt.splice(index, 1);
        })
        .catch((_) => {});
    },
    delectClassfyHandle(i) {
      this.$confirm(
        `确认删除分类名称【${this.dataForm.childTypeList[i].classfyName}】此条数据？`,
        "提示",
        { type: "warning" }
      )
        .then((_) => {
          this.dataForm.childTypeList.splice(i, 1);
        })
        .catch((_) => {});
    },
    // 配置组合
    selectSubInvestHandle(i, index, type) {
      this.strategy_i = i;
      this.strategy_index = index;
      this.investTypeDialog = type;
      this.subInvestVisible = true;
      this.$nextTick(() => {
        this.$refs.subInvestOpen.init();
      });
    },
    // 新建投资
    addOrUpdateHandle(i) {
      this.combination_i = i;
      this.investAddOrUpdateView = true;
    },
    // 投资组合配置单选
    selctSubInvestName(params) {
      this.dataForm.childTypeList[this.strategy_i].classifyStrategyExt[
        this.strategy_index
      ].strategyId = params.investId;
      this.dataForm.childTypeList[this.strategy_i].classifyStrategyExt[
        this.strategy_index
      ].strategyName = params.investName;
      this.dataForm.childTypeList[this.strategy_i].classifyStrategyExt[
        this.strategy_index
      ].currentShare = params.currentShare;
      this.dataForm.childTypeList[this.strategy_i].classifyStrategyExt[
        this.strategy_index
      ].currentEquity = params.currentEquity;
      this.dataForm.childTypeList[this.strategy_i].classifyStrategyExt[
        this.strategy_index
      ].enterTime = params.enterTime;
      this.dataForm.childTypeList[this.strategy_i].classifyStrategyExt[
        this.strategy_index
      ].strategyNameRule = false;
      // if (!this.defCreatedTime) {
      if (
        !this.dataForm.createdTime ||
        new Date(params.enterTime) < new Date(this.dataForm.createdTime)
      ) {
        console.log(parseTime(new Date()));
        this.dataForm.createdTime = params.enterTime || parseTime(new Date());
      } else {
        this.dataForm.createdTime = parseTime(new Date());
      }
      // }
    },
    // 投资组合配置多选
    selCheckctSubInvestName(checkList) {
      for (var i = 0; i < checkList.length; i++) {
        this.dataForm.childTypeList[this.strategy_i].classifyStrategyExt.push({
          strategyId: checkList[i].investId,
          strategyName: checkList[i].investName,
          enterTime: checkList[i].enterTime,
          currentShare: checkList[i].currentShare,
          currentEquity: checkList[i].currentEquity,
        });
        if (
          !this.dataForm.createdTime ||
          new Date(checkList[i].enterTime) < new Date(this.dataForm.createdTime)
        ) {
          this.dataForm.createdTime =
            checkList[i].enterTime || parseTime(new Date());
        }
      }
    },
    async submitHandle() {
      this.dataForm.childTypeList.map((item, i) => {
        if (item.classifyStrategyExt.length === 0) {
          this.$message({
            message: "子投资分类至少需要选择一个子投资",
            type: "warning",
          });
          return;
        }
      });
      if (
        (await this.checkDataFromSubmit()) ||
        (await this.checkChildTypeListLength())
      ) {
        return;
      }
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.dataForm.createdBy = this.userId;
          configInvestComposition({
            strategyClassifyVo: this.copyArr(this.dataForm.childTypeList),
            strategyCompositionVo: { ...this.copyObject(this.dataForm) },
          }).then((res) => {
            this.$emit("closeOpen");
            this.dialogClose();
            this.$message({
              message: res.msg,
              type: "success",
            });
          });
        }
      });
    },
    async checkDataFromSubmit() {
      // 非空校验
      let noEmpty = false;
      /**
       * 总资产金额 与 持仓份额
       */
      this.dataForm.investManageEquity = 0;
      this.dataForm.investManageShare = 0;

      this.dataForm.childTypeList.map((item, i) => {
        for (const key in item) {
          if (key === "classfyName" || key === "indexType") {
            if (!item[key]) {
              noEmpty = true;
              this.$set(this.dataForm.childTypeList[i], `${key}Rule`, true);
            }
          }
        }
        let investManageEquity = 0;
        let investManageShare = 0;
        item.classifyStrategyExt.map((citem, index) => {
          /**
           * 计算 总资产金额 与 持仓份额
           */
          this.dataForm.investManageEquity += this.checkNumber(
            citem.currentEquity || ""
          );
          this.dataForm.investManageShare += this.checkNumber(
            citem.currentShare || ""
          );
          /** end */
          /**
           * 计算分类 份额 与 权益
           */

          investManageEquity += this.checkNumber(citem.currentEquity || "");
          investManageShare += this.checkNumber(citem.currentShare || "");
          /** end */
          for (const key in citem) {
            if (key === "strategyName") {
              if (!citem[key]) {
                noEmpty = true;
                this.$set(
                  this.dataForm.childTypeList[i].classifyStrategyExt[index],
                  `${key}Rule`,
                  true
                );
              }
            }
          }
        });
        this.$set(
          this.dataForm.childTypeList[i],
          "investManageEquity",
          investManageEquity
        );
        this.$set(
          this.dataForm.childTypeList[i],
          "investManageShare",
          investManageShare
        );
      });
      if (noEmpty) {
        console.log(noEmpty);
        this.$message.closeAll();
        this.$message({
          message: "存在未填项",
          type: "warning",
        });
        return true;
      }

      if (this.repeatName()) {
        this.$message.closeAll();
        this.$message({
          message: "组合或分类名称不能重复",
          type: "warning",
        });
        return true;
      }
      return false;
    },
    async checkChildTypeListLength() {
      let check = false;
      this.dataForm.childTypeList.map((item, i) => {
        if (item.classifyStrategyExt.length === 0) {
          this.$message.closeAll();
          this.$message({
            message: "子投资分类至少需要选择一个子投资",
            type: "warning",
          });
          check = true;
        }
      });
      return check;
    },
    // 名称重复校验
    repeatName() {
      let nameCheck = false;
      const nameObj = {};
      nameObj[this.dataForm.compositionName] = true;
      this.dataForm.childTypeList.map((item, i) => {
        if (nameObj[item.classfyName]) {
          nameCheck = true;
          this.$set(this.dataForm.childTypeList[i], `classfyNameRule`, true);
        }
        nameObj[item.classfyName] = true;
      });
      return nameCheck;
    },

    // 输入框非空校验
    checkNoEmpty(i, name, childName, index) {
      console.log(this.dataForm.childTypeList[i]);
      if (childName) {
        if (this.dataForm.childTypeList[i][childName][index][name]) {
          this.$set(
            this.dataForm.childTypeList[i][childName][index],
            `${name}Rule`,
            false
          );
        }
      } else {
        if (this.dataForm.childTypeList[i][name]) {
          this.$set(this.dataForm.childTypeList[i], `${name}Rule`, false);
        }
      }
    },
    // 过滤非数字
    checkNumber(value) {
      value = value.toString();
      value = value.replace(/[^\d.]/g, "");
      value = value.replace(/^\./g, "");
      value = value.replace(/\.{2,}/g, ".");
      value = value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
      return +value;
    },
    copyArr(arr) {
      const res = [];
      for (let i = 0; i < arr.length; i++) {
        res.push(arr[i]);
      }
      return res;
    },
    copyObject(obj) {
      const res = {};
      for (const key in obj) {
        if (Object.hasOwnProperty.call(obj, key)) {
          res[key] = obj[key];
        }
      }
      return res;
    },
    getIndexNameHandle(val) {
      this.dataForm.indexName = val;
    },
    dialogClose() {
      this.$emit("update:addOrUpdateView", false);
    },
  },
};
</script>
<style lang="scss">
.aMDialog {
  .el-dialog__header {
    .el-dialog__title {
      font-weight: bold;
    }
    .el-dialog__close {
      font-size: 20px;
    }
  }
  .el-dialog__body {
    padding: 16px 20px;
    color: rgba(0, 0, 0, 0.75);
    border-top: 1px solid #f0f0f0;
  }
}
.aMFrom {
  .el-form-item__error {
    padding-top: 2px;
  }
}
.append-style {
  .el-input-group__append {
    padding: 0 10px;
  }
}
</style>
<style scoped lang="scss">
.app-container {
  .container {
    padding: 0;
  }
  .footer {
    margin-top: 40px;
    text-align: center;
  }
  .card-list {
    border-top: 1px solid rgba(240, 240, 240, 1);
    padding: 15px 0;
    .tit {
      font-size: 18px;
      font-weight: bold;
      color: rgba(0, 0, 0, 0.75);
    }
    .card-list-title {
      display: flex;
      background: #f5f5f5;
      font-weight: bold;
      height: 37px;
      font-size: 14px;
      padding-top: 4px;
      justify-content: space-between;
      .iconfont {
        font-size: 14px;
      }
    }
    &-content {
      margin-top: 14px;
      padding: 0 0 20px 0;
      border: 1px solid #ebebeb;
      &-title {
        margin: 10px;
        display: flex;
        background: #f5f7fa;
        color: #666;
        font-weight: bold;
        line-height: 37px;
        justify-content: space-between;
        border-bottom: 1px solid #ebeef5;
      }
      &-child {
        margin: 6px 10px 0 10px;
        padding-bottom: 6px;
        display: flex;
        border-bottom: 1px solid #ebeef5;
        justify-content: space-between;
        .icon-move {
          cursor: pointer;
          font-size: 21px;
          width: 40px;
          display: inline-block;
          line-height: 28px;
        }
      }
    }
  }
  .card {
    position: relative;
    border: 1px solid #ddd;
    & + .card {
      margin-top: 22px;
    }
    .card-tit {
      display: flex;
      justify-content: space-between;
      align-items: center;
      line-height: 34px;
      background: #eee;
      padding: 0 12px;
      font-weight: bold;
      margin-bottom: 22px;
      .close {
        width: 20px;
        line-height: 20px;
        text-align: center;
        background: #ff3300;
        color: #fff;
        border-radius: 50%;
        cursor: pointer;
      }
    }
  }
  .dialog-footer {
    margin-top: 35px;
    padding-top: 16px;
    border-top: 1px solid #f0f0f0;
    text-align: right;
  }
}
</style>
